//
//  ClientLogin.m
//  Feeder
//
//  Created by Diego Acosta on 7/30/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ClientLogin.h"
#import "WebServiceInterfaceProtected.h"

// service specific macros.
#define kClientLoginURL @"https://www.google.com/accounts/ClientLogin"
#define kClientLoginMethod HTTPMethodGet

// auth error domain
#define kClientLoginErrorDomain @"ClientLoginErrorDomain"

typedef enum {
	
	LoginBadAuthentication,
	LoginNotVerified,
	LoginTermsNotAgreed,
	LoginCaptchaRequired,
	LoginUnknown,
	LoginAccountDeleted,
	LoginAccountDisabled,
	LoginServiceDisabled,
	LoginServiceUnavailable	
} LoginError;

@interface ClientLogin(Private)

- (NSDictionary *)_parseResponse:(NSString *)response;
- (void)_processResponse:(NSDictionary *)dict;
- (NSError *)_errorFromString:(NSString *)error;

@end

@implementation ClientLogin

@synthesize delegate;

- (id)init {

	if (self = [super init]) {
		
		service = self;
	}
	
	return self;
}

#pragma mark -
#pragma mark Public methods

- (void)submitWithUsername:(NSString *)username andPassword:(NSString *)password {

	// create request url.
	NSString * url = [NSString stringWithFormat:@"%@?service=reader&Email=%@&Passwd=%@",
					  kClientLoginURL,
					  username,
					  password];
	
	// submit.
	[super _submitWithURL:url
				andMethod:kClientLoginMethod];
}

#pragma mark -
#pragma mark Private methods

- (NSDictionary *)_parseResponse:(NSString *)response {

	NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
	
	NSArray * items = [response componentsSeparatedByString:@"\n"];
	for (int i = 0; i < [items count] - 1; i++) {
		
		NSString * item = [items objectAtIndex:i];
		
		NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:@"="];
		NSRange range = [item rangeOfCharacterFromSet:set];
		
		// getting item components.
		NSString * key = [item substringToIndex:range.location];
		NSString * value = [item substringFromIndex:range.location + 1];
		
		// add into dictionary.
		[dict setObject:value forKey:key];
	}
	
	return (NSDictionary *)dict;
}

- (void)_processResponse:(NSDictionary *)dict {

	NSString * err = [dict objectForKey:@"Error"];
	
	// check for errors.
	if (err != nil) {
		
		NSError * error = [self _errorFromString:err];
		
		// notify delegate about the error.
		[delegate loginFailedWithError:error];
		return;
	}
	
	// notify delegate with response.
	[delegate loginSucceeded:dict];
}

- (NSError *)_errorFromString:(NSString *)error {
	
	NSDictionary * detail = [NSMutableDictionary dictionary];
	
	[detail setValue:error
			  forKey:NSLocalizedDescriptionKey];
	
	return [NSError errorWithDomain:kClientLoginErrorDomain
							   code:LoginBadAuthentication
						   userInfo:detail];
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate methods

- (void)requestFinished:(ASIHTTPRequest *)request {

	// get response string.
	NSString * resp = [request responseString];
	
	// parse response.
	NSDictionary * dict = [self _parseResponse:resp];
	
	// process response
	[self _processResponse:dict];
}

- (void)requestFailed:(ASIHTTPRequest *)request {
	
	return;
}

#pragma mark -

- (void)dealloc {

	[delegate release];
	[super dealloc];
}

@end
